package com;

import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;

@HandlesTypes(ApplicationInitializer.class)
public class MyServletContainerInitializer implements ServletContainerInitializer {

	@Override
	public void onStartup(Set<Class<?>> applicationInitializers, ServletContext ctx) throws ServletException {
		System.out.println("...MyServletContainerInitializer...");
		
		List<ApplicationInitializer> initializers = new LinkedList<>();
		
		if (applicationInitializers == null) {
			System.out.println("applicationInitializers is null");
			return;
		}
		
		for (Class<?> waiClass : applicationInitializers) {
			if (waiClass.isInterface() || Modifier.isAbstract(waiClass.getModifiers())){
				continue;
			}
			
			try {
				initializers.add((ApplicationInitializer)waiClass.newInstance());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		if (initializers.isEmpty()){
			System.out.println("No ApplicationInitializer types detected on classpath");
			return;
		}
		
		System.out.println("ApplicationInitializer detected on classpath: " + initializers);
		
		for (ApplicationInitializer initializer : initializers) {
			initializer.onStartup();
		}
	}

}
